package com.mcx.modules.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class SocketDispatcher {
    private static SocketDispatcher instance;
    public static SocketDispatcher getInstance() {
        if (instance == null) {
            instance = new SocketDispatcher();
        }
        return instance;
    }

    // 委托字典
    private HashMap<Short, ArrayList<OnNetActionHandler>> dic = new HashMap<Short, ArrayList<OnNetActionHandler>>();

    /**
     * 添加监听
     * @param protoCode
     * @param handler
     */
    public void AddEventListener(short protoCode, OnNetActionHandler handler)
    {
        if (dic.containsKey(protoCode))
        {
            dic.get(protoCode).add(handler);
        }
        else
        {
            ArrayList<OnNetActionHandler> lstHandler = new ArrayList<OnNetActionHandler>();
            lstHandler.add(handler);
            dic.put(protoCode, lstHandler);
        }
    }

    /**
     * 移除监听
     * @param protoCode
     * @param handler
     */
    public void RemoveEventListener(short protoCode, OnNetActionHandler handler)
    {
        if (dic.containsKey(protoCode))
        {
            ArrayList<OnNetActionHandler> lstHandler = dic.get(protoCode);
            lstHandler.remove(handler);
            if (lstHandler.size() == 0)
            {
                dic.remove(protoCode);
            }
        }
    }

    /**
     * 派发协议
     * @param protoCode
     * @param buffer
     */
    public void Dispatch(short protoCode, byte[] buffer) throws IOException {
        if (dic.containsKey(protoCode))
        {
            ArrayList<OnNetActionHandler> lstHandler = dic.get(protoCode);
            if (lstHandler != null && lstHandler.size() > 0)
            {
                for (int i = 0; i < lstHandler.size(); i++)
                {
                    if (lstHandler.get(i) != null)
                    {
                        lstHandler.get(i).dispatch(buffer);
                    }
                }
            }
        }
    }
}
